package neu.soft.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import neu.soft.constant.PurchaseOrderType;
import neu.soft.entity.FinancialPurchaseOrder;
import neu.soft.entity.GoodInfo;
import neu.soft.exception.AppException;
import neu.soft.exception.AppExceptionCodeMsg;
import neu.soft.mapper.PurchaseOrderMapper;
import neu.soft.query.BasePageQuery;
import neu.soft.service.PurchaseService;
import neu.soft.util.TypeConvert;
import neu.soft.vo.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PurchaseServiceImpl implements PurchaseService {

    @Autowired
    PurchaseOrderMapper purchaseOrderMapper;

    @Override
    public boolean purchaseReview(Integer purchaseOrderId) {
        return false;
    }

    @Override
    public void addPurchaseOrder(FinancialPurchaseOrder financialPurchaseOrder) {
        if (financialPurchaseOrder == null) {
            throw new AppException(AppExceptionCodeMsg.DZYJ_NGDZ);
        }
        int res = purchaseOrderMapper.addPurchaseOrder(financialPurchaseOrder);
        if (res < 1) {
            throw new AppException(AppExceptionCodeMsg.DZYJ_NGDZ);
        }
    }

    @Override
    public FinancialPurchaseOrder findById(Integer financialOrderId) {
        return purchaseOrderMapper.findById(financialOrderId);
    }

    @Override
    public void batchInsertGoodInfo(List<GoodInfo> goodInfoList) {
        purchaseOrderMapper.batchInsertGoodInfo(goodInfoList);
    }

    @Override
    public PageBean<FinancialPurchaseOrder> findByPage(BasePageQuery query) {

        PageBean<FinancialPurchaseOrder> pageBean = new PageBean<>();
        PageHelper.startPage(query.getPageNow(), query.getPageSize());
        List<FinancialPurchaseOrder> financialPurchaseOrderList = purchaseOrderMapper.findByPage(query);
        financialPurchaseOrderList.forEach(financialPurchaseOrder -> {
            String type = TypeConvert.enumToString(PurchaseOrderType.class, financialPurchaseOrder.getPurchaseType());
            financialPurchaseOrder.setPurchaseType(type);
        });
        PageInfo<FinancialPurchaseOrder> pageInfo = new PageInfo<>(financialPurchaseOrderList);
        pageInfo.setTotal(financialPurchaseOrderList.size());
        pageBean.setTotalRows(pageInfo.getTotal());
        pageBean.setTotalPages(pageInfo.getPages());
        pageBean.setRowData(pageInfo.getList());
        return pageBean;
    }


}
